"use client";

import { useState } from "react";
import { PlusCircle, ChevronDown, Users, Shield } from "lucide-react";

import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { UserTab } from "@/components/permissions/UserTab";
import { RoleTab } from "@/components/permissions/RoleTab";
import { AddUserDialog } from "@/components/permissions/AddUserDialog";
import { BulkAddUsersDialog } from "@/components/permissions/BulkAddUsersDialog";

// 模拟用户数据
const users = [
  {
    id: 1,
    name: "张三",
    email: "zhangsan@example.com",
    role: "管理员",
    permissions: {
      view: true,
      edit: true,
      delete: true,
      share: true,
    },
    lastActive: "2023-05-15T14:30:00",
  },
  {
    id: 2,
    name: "李四",
    email: "lisi@example.com",
    role: "编辑者",
    permissions: {
      view: true,
      edit: true,
      delete: false,
      share: true,
    },
    lastActive: "2023-05-16T09:45:00",
  },
  {
    id: 3,
    name: "王五",
    email: "wangwu@example.com",
    role: "查看者",
    permissions: {
      view: true,
      edit: false,
      delete: false,
      share: false,
    },
    lastActive: "2023-05-14T16:20:00",
  },
  // 可以添加更多用户
];

// 角色定义
const roles = [
  { id: 1, name: "管理员", description: "拥有所有权限" },
  { id: 2, name: "编辑者", description: "可以查看和编辑内容" },
  { id: 3, name: "查看者", description: "只能查看内容" },
];

export default function PermissionsPage() {
  const [searchQuery, setSearchQuery] = useState("");
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [selectedUser, setSelectedUser] = useState(null);
  const [showAddUserDialog, setShowAddUserDialog] = useState(false);
  const [showBulkAddDialog, setShowBulkAddDialog] = useState(false);
  const [availableRoles, setAvailableRoles] = useState(roles);

  const handleEditUser = (user) => {
    setSelectedUser(user);
    setShowEditDialog(true);
  };

  const handleDeleteRole = (roleId) => {
    // 过滤掉要删除的角色
    setAvailableRoles(availableRoles.filter((role) => role.id !== roleId));
    // 在实际应用中，这里应该有一个API调用来删除角色
  };

  const handleEditRole = (roleId, updatedRole) => {
    // 更新角色信息
    setAvailableRoles(
      availableRoles.map((role) =>
        role.id === roleId ? { ...role, ...updatedRole } : role
      )
    );
    // 在实际应用中，这里应该有一个API调用来更新角色
  };

  const filteredUsers = users.filter(
    (user) =>
      user.name.includes(searchQuery) ||
      user.email.includes(searchQuery) ||
      user.role.includes(searchQuery)
  );

  return (
    <div className='container mx-auto py-6'>
      <div className='flex justify-between items-center mb-6'>
        <div>
          <h1 className='text-3xl font-bold'>权限管理</h1>
          <p className='text-muted-foreground'>管理用户权限和角色分配</p>
        </div>
        <div className='flex gap-2'>
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button>
                <PlusCircle className='mr-2 h-4 w-4' />
                添加用户
                <ChevronDown className='ml-2 h-4 w-4' />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent>
              <DropdownMenuItem onClick={() => setShowAddUserDialog(true)}>
                添加单个用户
              </DropdownMenuItem>
              <DropdownMenuItem onClick={() => setShowBulkAddDialog(true)}>
                批量添加用户
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </div>
      </div>

      <Tabs defaultValue='users' className='mb-6'>
        <TabsList>
          <TabsTrigger value='users' className='flex items-center'>
            <Users className='mr-2 h-4 w-4' />
            用户
          </TabsTrigger>
          <TabsTrigger value='roles' className='flex items-center'>
            <Shield className='mr-2 h-4 w-4' />
            角色
          </TabsTrigger>
        </TabsList>

        <TabsContent value='users'>
          <UserTab
            users={filteredUsers}
            searchQuery={searchQuery}
            setSearchQuery={setSearchQuery}
            onEditUser={handleEditUser}
          />
        </TabsContent>

        <TabsContent value='roles'>
          <RoleTab
            roles={availableRoles}
            users={users}
            onDeleteRole={handleDeleteRole}
            onEditRole={handleEditRole}
          />
        </TabsContent>
      </Tabs>

      <Dialog open={showEditDialog} onOpenChange={setShowEditDialog}>
        <DialogContent className='sm:max-w-[500px]'>
          <DialogHeader>
            <DialogTitle>编辑用户权限</DialogTitle>
            <DialogDescription>
              修改用户的权限和角色。更改将即时生效。
            </DialogDescription>
          </DialogHeader>

          {selectedUser && (
            <div className='grid gap-4 py-4'>
              <div className='grid grid-cols-4 items-center gap-4'>
                <Label htmlFor='user-name' className='text-right'>
                  用户
                </Label>
                <div className='col-span-3'>
                  <div className='font-medium'>{selectedUser.name}</div>
                  <div className='text-sm text-muted-foreground'>
                    {selectedUser.email}
                  </div>
                </div>
              </div>

              <div className='grid grid-cols-4 items-center gap-4'>
                <Label htmlFor='role' className='text-right'>
                  角色
                </Label>
                <Select defaultValue={selectedUser.role} className='col-span-3'>
                  <SelectTrigger>
                    <SelectValue placeholder='选择角色' />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value='管理员'>管理员</SelectItem>
                    <SelectItem value='编辑者'>编辑者</SelectItem>
                    <SelectItem value='查看者'>查看者</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div className='grid grid-cols-4 items-start gap-4'>
                <Label className='text-right pt-2'>权限</Label>
                <div className='col-span-3 space-y-3'>
                  <div className='flex items-center space-x-2'>
                    <Checkbox
                      id='view'
                      defaultChecked={selectedUser.permissions.view}
                    />
                    <Label htmlFor='view'>查看</Label>
                  </div>
                  <div className='flex items-center space-x-2'>
                    <Checkbox
                      id='edit'
                      defaultChecked={selectedUser.permissions.edit}
                    />
                    <Label htmlFor='edit'>编辑</Label>
                  </div>
                  <div className='flex items-center space-x-2'>
                    <Checkbox
                      id='delete'
                      defaultChecked={selectedUser.permissions.delete}
                    />
                    <Label htmlFor='delete'>删除</Label>
                  </div>
                  <div className='flex items-center space-x-2'>
                    <Checkbox
                      id='share'
                      defaultChecked={selectedUser.permissions.share}
                    />
                    <Label htmlFor='share'>分享</Label>
                  </div>
                </div>
              </div>
            </div>
          )}

          <DialogFooter>
            <Button variant='outline' onClick={() => setShowEditDialog(false)}>
              取消
            </Button>
            <Button onClick={() => setShowEditDialog(false)}>保存更改</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 添加用户对话框 */}
      <AddUserDialog
        open={showAddUserDialog}
        onOpenChange={setShowAddUserDialog}
      />

      {/* 批量添加用户对话框 */}
      <BulkAddUsersDialog
        open={showBulkAddDialog}
        onOpenChange={setShowBulkAddDialog}
      />
    </div>
  );
}
